package com.alan.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;

/**
 * @author weiBin
 * @date 2018/11/20
 */
public class HttpServer {
    private void openServer(int port) throws InterruptedException {
        ServerBootstrap b = new ServerBootstrap();
        EventLoopGroup boos = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();
        b.group(boos, worker).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                //Request 解码
                pipeline.addLast("http-decoder", new HttpRequestDecoder());
                //Response 编码
                pipeline.addLast("http-encoder", new HttpResponseEncoder());
                //业务处理
                pipeline.addLast("server-handler", new HttpServerHandler());
            }
        });
        try {
            //启动服务监听
            ChannelFuture future = b.bind(port).sync();
            System.out.println("服务启动开始监听" + port);
            future.channel().closeFuture().sync();
        } finally {
            //优雅退出线程池
            boos.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        try {
            new HttpServer().openServer(8080);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    class HttpServerHandler extends SimpleChannelInboundHandler {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {
            if (o instanceof LastHttpContent) {
                DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
                response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=utf-8");
                String src = "<!DOCTYPE html>\n" +
                        "<html lang=\"en\">\n" +
                        "<head>\n" +
                        "    <meta charset=\"UTF-8\">\n" +
                        "    <title>hello word</title>\n" +
                        "</head>\n" +
                        "<body>\n" +
                        "hello word\n" +
                        "</body>\n" +
                        "</html>";
                response.content().writeBytes(src.getBytes(CharsetUtil.UTF_8));
                ChannelFuture future = ctx.writeAndFlush(response);
                future.addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}
